package cn.com.fuhuitong.main.host.ui.activity

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import cn.com.fuhuitong.R
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.MainType
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.cart.ui.fragment.CartFragment
import cn.com.fuhuitong.main.cate.ui.fragment.CategoryFragment
import cn.com.fuhuitong.main.home.ui.fragment.HomeFragment
import cn.com.fuhuitong.main.host.adapter.MainStatePagerAdapter
import cn.com.fuhuitong.main.host.vm.MainViewModel
import cn.com.fuhuitong.main.mine.ui.fragment.MineFragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import kotlinx.android.synthetic.main.activity_main.*

@Route(path = ARouteConstance.ACTIVITY_URL_MAIN)
class MainActivity : ViewModeActivity<MainViewModel>() {

    override fun viewModel(): MainViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_main

    override fun initView() {

        val mainFragments: MutableList<Fragment> = mutableListOf(
            HomeFragment(), CategoryFragment(), CartFragment(), MineFragment()
        )
        val mainStatePager = MainStatePagerAdapter(
            supportFragmentManager,
            FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
            mainFragments
        )
        view_pager.setScrollAnim(false)
        view_pager.adapter = mainStatePager

        nav_view.setOnNavigationItemSelectedListener { item ->
            val position = when (item.itemId) {
                R.id.item_main_category -> 1
                R.id.item_main_cart -> 2
                R.id.item_main_mine -> 3
                else -> 0
            }
            view_pager.currentItem = position
            return@setOnNavigationItemSelectedListener true
        }
    }

    override fun onEventMainThread(eventBus: MainBean<*, *>) {
        super.onEventMainThread(eventBus)
        if (eventBus.type !is MainType)
            return
        ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MAIN)
            .navigation()
        nav_view.selectedItemId = nav_view.menu.getItem(0).itemId
    }

}